package com.tpc.eb.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.tpc.eb.bean.Business;
import com.tpc.eb.bean.JSONToBusiness;
import com.tpc.eb.job.BusinessQuartz;
import com.tpc.eb.module.AppModel;
import com.tpc.eb.service.BusinessService;
import com.tpc.eb.utils.AlertUtil;
import com.tpc.eb.utils.FileUtil;
import com.tpc.eb.utils.JDBCUtil;
import de.felixroske.jfxsupport.FXMLController;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import lombok.extern.slf4j.Slf4j;
import org.ini4j.Profile;
import org.quartz.SchedulerException;


import java.io.IOException;
import java.net.URL;
import java.sql.Connection;
import java.util.*;


@Slf4j
@FXMLController

public class FormMainController<T> implements Initializable {


    @FXML
    private Tab tabLog;

    @FXML
    private Tab tabInterface;

    @FXML
    private Tab tabDBConfig;

    @FXML
    private Tab tabServerConfig;


    @FXML
    private TabPane tabPaneOMS;

    @FXML
    private Button butStartJob;

    @FXML
    private Button butStopJob;

    @FXML
    private Button butClearJobLog;

    @FXML
    public  TextArea textALog;

    @FXML
    private TextField textFOMSUrl;

    @FXML
    private TextField textFOMSAppKety;

    @FXML
    private TextField textFOMSAppSecret;

    @FXML
    private ComboBox<String> comDBType;

    @FXML
    private TextField textFOMSName;

    @FXML
    private TextField textFServer;

    @FXML
    private TextField textFUserName;

    @FXML
    private TextField textFPassWord;

    @FXML
    private TextField textFDataBase;

    @FXML
    private TextField textFPort;

    @FXML
    private TextField textFPlan;

    @FXML
    private TextField textFBusinessType;

    @FXML
    private TextField textFNode;

    @FXML
    private TextField textFCode;

    @FXML
    private ComboBox<String> comInterfaceType;

    @FXML
    private TableView<Business> tableVInterface;

    @FXML
    private TableColumn<Business, String> businessType;

    @FXML
    private TableColumn<Business, String> node;

    @FXML
    private TableColumn<Business, String> plan;

    @FXML
    private TextField textFOMSMethod;

    @FXML
    private TableColumn<Business, String> interfaceType;

    @FXML
    private TableColumn<Business, String> code;

    @FXML
    private ComboBox<String> comBusinessType;

    @FXML
    private TextArea textAPullSql;

    @FXML
    private TextField textFBackSql;



    @FXML
    private ComboBox<String> comOMSType;

//    @Autowired
//    private BusinessQuartz<T> businessQuartz;

    String filePath = "";
    String oldBusinessType = "";
    String infoMess = "";

    public  static AppModel model = new AppModel();

    @FXML
    void butClearJobLogClick(ActionEvent event) {
        textALog.setText("");
    }

    @FXML
    void butStartJobClick(ActionEvent event)  {
        BusinessService businessService = new BusinessService();
        try {
            businessService.businessService();
            butStartJob.setDisable(true);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SchedulerException e) {
            e.printStackTrace();
        }

    }

    public void printLog(String message){
        textALog.appendText(message + "\n");
    }

    @FXML
    void butStopJobClck(ActionEvent event) throws SchedulerException {
        BusinessQuartz<T> businessQuartz = new BusinessQuartz<>();
        businessQuartz.businessJobStop();
        butStartJob.setDisable(false);
    }

    public static void setText(String text)
    {
        model.setText(text);
    }

    //界面初始化
    @Override
    public void initialize(URL location, ResourceBundle resources) {

        //给ComboBox 设置初始值
        ObservableList<String> dbTypeList = FXCollections.observableArrayList("MSSQL", "ORACLE","MYSQL");
        comDBType.setItems(dbTypeList);

        List omsMethod = FileUtil.getOMSMethod();

        if(omsMethod!=null){
            ObservableList<String> interfaceTypeList = FXCollections.observableArrayList(omsMethod);
            comInterfaceType.setItems(interfaceTypeList);
        }


        ObservableList<String> omsTypeList = FXCollections.observableArrayList("企业", "机构");
        comOMSType.setItems(omsTypeList);

        comOMSType.setVisible(false);


        model.textProperty().addListener((obs, oldText, newText) -> textALog.appendText(newText + "\n"));

        //展现OMS配置
        showOMSServic();
        //展现数据库配置
        showDBServer();
        //接口定义双击事件
        doubleClickTableView();
        //tabPane监听
        changeTabPane();
    }

    //OMS配置信息保存
    @FXML
    void butOMSServiceSaveClick(ActionEvent event)  {
        String omsUrl = textFOMSUrl.getText();
        String omsAppKey = textFOMSAppKety.getText();
        String omsAppSecret =textFOMSAppSecret.getText();
        String omsType = comOMSType.getValue();
        String omsMethod = textFOMSMethod.getText();
        String omsName = textFOMSName.getText();
        Map<String,String> map = new HashMap<>();
        map.put("URL",omsUrl);
        map.put("AppKey",omsAppKey);
        map.put("AppSecret",omsAppSecret);
        map.put("Method",omsMethod);
        map.put("Name",omsName);
        try {
            FileUtil.saveConfig("OMSConfig",map);
            AlertUtil.SUCCESS();
        } catch (IOException e) {
            AlertUtil.FAIL(e.getMessage());
            e.printStackTrace();
        }
    }

    //数据库配置信息保存
    @FXML
    void butDBServerSaveClick(ActionEvent event) {
        String dbType = comDBType.getValue();
        String server = textFServer.getText();
        String userName = textFUserName.getText();
        String passWord =textFPassWord.getText();
        String dataBase = textFDataBase.getText();
        String port = textFPort.getText();
        Map<String,String> map = new HashMap<>();
        map.put("dbType",dbType);
        map.put("server",server);
        map.put("userName",userName);
        map.put("passWord",passWord);
        map.put("dataBase",dataBase);
        map.put("port",port);
        try {
            FileUtil.saveConfig("DBConfig",map);
            AlertUtil.SUCCESS();
        } catch (IOException e) {
            AlertUtil.FAIL(e.getMessage());
            e.printStackTrace();
        }
    }

    //展现OMS配置信息
    public void showOMSServic(){
        try {
            Map<String,String> map = FileUtil.getOMSConfig();
            String omsUrl = map.get("URL");
            String omsAppKey = map.get("AppKey");
            String omsAppSecret = map.get("AppSecret");
            String omsType = map.get("AppType");
            String omsMethod = map.get("Method");
            String omsSignNo = map.get("SignNo");
            String omsName = map.get("Name");
            textFOMSUrl.setText(omsUrl);
            textFOMSAppKety.setText(omsAppKey);
            textFOMSAppSecret.setText(omsAppSecret);
            comOMSType.setValue(omsType);
            textFOMSMethod.setText(omsMethod);
            textFOMSName.setText(omsName);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //展现数据库配置信息
    public void showDBServer(){
        try {
            Map<String,String> map = FileUtil.getDBConfig();
            String dbType = map.get("dbType");
            String server = map.get("server");
            String userName = map.get("userName");
            String passWord = map.get("passWord");
            String dataBase = map.get("dataBase");
            String port = map.get("port");
            comDBType.setValue(dbType);
            textFServer.setText(server);
            textFUserName.setText(userName);
            textFPassWord.setText(passWord);
            textFDataBase.setText(dataBase);
            textFPort.setText(port);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //数据库链接测试
    @FXML
    void butDBServerTestClick(ActionEvent event) {
        Connection connection = null ;
        try {
            connection = JDBCUtil.getConnection();
            AlertUtil.alert("数据库连接成功！");
        } catch (Exception e) {
            AlertUtil.FAIL("数据库链接失败！",e.getMessage());
        }finally {
            JDBCUtil.close(connection);
        }
    }

    //业务类型新增赋值为空
    @FXML
    void butBusinessTypeAddClick(ActionEvent event) {
        textFBusinessType.setDisable(false);
        oldBusinessType = "";
        textFBusinessType.setText("");
        textFNode.setText("");
        comInterfaceType.setValue("");
        textFCode.setText("");
        textFPlan.setText("");
    }

    //业务类型删除
    @FXML
    void butBusinessTypeDelClick(ActionEvent event) {
        try {
            String businessType = textFBusinessType.getText();
            if(businessType.length()==0){
                AlertUtil.FAIL("删除失败！","业务类型为空，请检查！");
            }else {
                FileUtil.removeConfig("BusinessType",businessType);
                AlertUtil.alert("删除成功");
            }
        } catch (IOException e) {
            AlertUtil.FAIL(e.getMessage());
            e.printStackTrace();
        }
        showInterface();
    }

    //业务类型保存
    @FXML
    void butBusinessTypeSaveClick(ActionEvent event) {
        JSONObject jsonObject = new JSONObject();
        String businessType = textFBusinessType.getText();
        String node = textFNode.getText();
        String interfaceType = comInterfaceType.getValue();
        String code = textFCode.getText();
        String plan = textFPlan.getText();
        jsonObject.put("businessType",businessType);
        jsonObject.put("node",node);
        jsonObject.put("interfaceType",interfaceType);
        jsonObject.put("code",code);
        jsonObject.put("plan",plan);

        if(businessType.trim().length()==0){
            AlertUtil.alert("请填写业务类型！");
            return;
        }

        if(node.trim().length()==0){
            AlertUtil.alert("请填写节点名称！");
            return;
        }

        if(interfaceType!=null || interfaceType.trim().length()==0){
            AlertUtil.alert("请选择接口类型！");
            return;
        }

        if(code.length()==0){
            AlertUtil.alert("请填写代码！");
            return;
        }

        if(plan.length()==0){
            AlertUtil.alert("请填写计划！");
            return;
        }

        try {
            FileUtil.removeConfig("BusinessType",oldBusinessType);
            FileUtil.addConfig("BusinessType",businessType,jsonObject.toJSONString());
            AlertUtil.SUCCESS();
        } catch (IOException e) {
            AlertUtil.FAIL(e.getMessage());
            e.printStackTrace();
        }
        showInterface();
    }

    //展现业务类型列表
    public void showInterface(){
        try {
            Profile.Section section = FileUtil.getInterfaceList("BusinessType");
            if(section!=null) {
                Set<Map.Entry<String, String>> setList = section.entrySet();
                ArrayList<Business> arrayList = new ArrayList<>();
                for (Map.Entry<String, String> mapList : setList) {
                    String business = mapList.getValue();
                    JSONToBusiness jsonToBusiness = JSON.parseObject(business, new TypeReference<JSONToBusiness>() {
                    });
                    Business bus = new Business();
                    bus.setBusinessType(jsonToBusiness.getBusinessType());
                    bus.setNode(jsonToBusiness.getNode());
                    bus.setInterfaceType(jsonToBusiness.getInterfaceType());
                    bus.setCode(jsonToBusiness.getCode());
                    bus.setPlan(jsonToBusiness.getPlan());
                    arrayList.add(bus);
                }
                ObservableList<Business> businessData =
                        FXCollections.observableArrayList(arrayList);
                this.businessType.setCellValueFactory(cellData -> cellData.getValue().businessTypeProperty());
                node.setCellValueFactory(cellData -> cellData.getValue().nodeProperty());
                interfaceType.setCellValueFactory(cellData -> cellData.getValue().interfaceTypeProperty());
                code.setCellValueFactory(cellData -> cellData.getValue().codeProperty());
                plan.setCellValueFactory(cellData -> cellData.getValue().planProperty());
                tableVInterface.setItems(businessData);
            }
        } catch (IOException e) {
            AlertUtil.FAIL(e.getMessage());
            e.printStackTrace();
        }
    }

    public void doubleClickTableView(){
        tableVInterface.setRowFactory( tv -> {
            TableRow<Business> row = new TableRow<Business>();
            row.setOnMouseClicked(event -> {
                if (event.getClickCount() == 2 && (! row.isEmpty()) ) {
                    Business business = row.getItem();
                    textFBusinessType.setText(business.getBusinessType());
                    textFNode.setText(business.getNode());
                    comInterfaceType.setValue(business.getInterfaceType());
                    textFCode.setText(business.getCode());
                    textFPlan.setText(business.getPlan());
                    oldBusinessType = business.getBusinessType();
                    textFBusinessType.setDisable(true);
                }
            });
            return row;
        });
    }

    //数据配置保存
    @FXML
    void butDBConfigSaveClick(ActionEvent event) {
        String businessType = comBusinessType.getValue();
        String PLAN = textFPlan.getText();
        String BACKSQL = textFBackSql.getText();
        ObservableList<CharSequence> sqlList = textAPullSql.getParagraphs();
        try {

            Map<String,String> map = new HashMap<>();
            map.put("PLAN",PLAN);
            map.put("BACKSQL",BACKSQL);
            for(int i=0;i<sqlList.size();i++){
                String sql = sqlList.get(i).toString();
                if(sql.length()>0) {
                    map.put("PULLSQL" + (i + 1),sql);
                }
            }
            FileUtil.removeConfig(businessType);
            FileUtil.saveConfig(businessType,map);
            AlertUtil.SUCCESS();
        } catch (IOException e) {
            AlertUtil.FAIL(e.getMessage());
            e.printStackTrace();
        }
    }

    //获取业务类型
    public void getBusinessType(){
        try {
            comBusinessType.setValue("");
            Profile.Section section = FileUtil.getInterfaceList("BusinessType");
            Set<String> keyList = section.keySet();
            ObservableList<String> businessTypeList = FXCollections.observableArrayList(keyList);
            if (businessTypeList.size()>0) {
                comBusinessType.setItems(businessTypeList);
            }
            textFPlan.setText("");
            textAPullSql.setText("");
            textFBackSql.setText("");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void changeTabPane(){
        tabPaneOMS.getSelectionModel().selectedItemProperty().addListener(new ChangeListener() {
            @Override
            public void changed(ObservableValue observable,Object oldValue, Object newValue) {
                if(newValue.equals(tabInterface)){
                    showInterface();
                }else if(newValue.equals(tabDBConfig)){
                    getBusinessType();
                }
            }
        });
    }

    //改变业务类型
    /*
    public void changeComBusinessType(){
        comBusinessType.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() {
            @Override
            public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
                String businessType = "";
                if(newValue!=null && newValue.length()>0) {
                    businessType = newValue;
                }
                try {
                    textFPlan.setText("");
                    textAPullSql.setText("");
                    textFBackSql.setText("");
                    Profile.Section section = FileUtil.getInterfaceList(businessType);
                    if(section!=null) {
                        Set<Map.Entry<String, String>> setList = section.entrySet();
                        Iterator<Map.Entry<String, String>> it = setList.iterator();
                        Map<String, String> mapList = new HashMap<>();
                        while (it.hasNext()) {
                            Map.Entry<String, String> map = it.next();
                            if (map.getKey().indexOf("PULLSQL") > -1) {
                                mapList.put(map.getKey(), map.getValue());
                            }
                            if (map.getKey().indexOf("PLAN") > -1) {
                                textFPlan.setText(map.getValue());
                            }
                            if (map.getKey().indexOf("BACKSQL") > -1) {
                                textFBackSql.setText(map.getValue());
                            }
                        }
                        log.info(mapList.toString());
                        for (int i = 0; i < mapList.size(); i++) {

                            String key = "PULLSQL" + (i+1);
                            log.info(mapList.get(key));
                            String value = mapList.get(key) != null ? mapList.get(key) : "";
                            if (value.length() > 0) {
                                textAPullSql.appendText(value + "\n");
                            }
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
    */
}
